﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Json
{
    internal class ObjectStorage
    {
        private readonly Stack<string> _pathStack = new Stack<string>();
        private readonly Dictionary<string, object> _objects = new Dictionary<string, object>();

        public string Path
        {
            get
            {
                var stringBuilder = new StringBuilder("this");
                var pathArray = _pathStack.ToArray();
                for (int i = pathArray.Length - 1; i >= 0; i--)
                {
                    stringBuilder.Append(pathArray[i]);
                }

                return stringBuilder.ToString();
            }
        }

        public void PushProperty(string property)
        {
            _pathStack.Push("." + property);   
        }

        public void PushIndex(int index)
        {
            _pathStack.Push("[" + index + "]");
        }

        public void AddObject(object instance)
        {
            _objects.Add(Path, instance);
        }

        public void Pop()
        {
            _pathStack.Pop();
        }

        public object GetObject(string path)
        {
            return _objects[path];
        }

        public bool ContainsPath(string path)
        {
            return _objects.ContainsKey(path);
        }

        public string StroredPath(object instance)
        {
            var record = _objects.FirstOrDefault(pair => pair.Value == instance);
            return (!string.IsNullOrEmpty(record.Key)) ? record.Key : string.Empty;
        }
    }
}